package com.sinosun.autotestmachine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.sinosun.autotestmachine.tools.TaskManager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

/**
 * 选择文件窗口
 * @author HYW
 *
 */
public class FileSelectActivity extends Activity {
	Button btnOk;		//按钮确定
	Button btnBack;		//按钮返回
	String path;		//文件路径
	ListView fileList;	//显示列表
	List<FileElement> content = new ArrayList<FileElement>();		//显示数据内容
	FileElement selected = null;
	int index = -1;
	FileAdapter adapter;			//文件列表适配器
	
	@Override public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = this.getIntent().getExtras();
		String path = bundle.getString(App.PATH);
		File file = new File(path);
		for (String filePath : file.list()) {
			FileElement ele = new FileElement(path + "/" + filePath);
			content.add(ele);
		}
		
		this.setContentView(R.layout.file_select_layout);
		btnOk = (Button) findViewById(R.id.btn_ok);
		btnBack = (Button) findViewById(R.id.btn_back);
		fileList = (ListView) findViewById(R.id.file_list);
		adapter = new FileAdapter(FileSelectActivity.this, content);
		
		fileList.setAdapter(adapter);
		btnOk.setOnClickListener(clickListener);
		btnBack.setOnClickListener(clickListener);
		adapter.setOnFileItemClickListener(fileItemClickListener);
	}
	
	private OnClickListener clickListener = new OnClickListener() {
		@Override public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_ok:
				if (index != -1) {
					TaskManager.getTaskManager().setTestFileDir(content.get(index).getFilePath());
					Intent intent = new Intent(FileSelectActivity.this, MainActivity.class);
					FileSelectActivity.this.startActivity(intent);
				}
				break;
			case R.id.btn_back:
				FileSelectActivity.this.finish();
				break;
			}
		}
	};
	
	private OnFileItemClickListener fileItemClickListener = new OnFileItemClickListener() {
		@Override public void onItemClicked(int pos) {
			if(!content.get(pos).IsFile()) {
				Bundle bundle = new Bundle();
				bundle.putString(App.PATH, content.get(pos).getFilePath());
				Intent intent = new Intent(FileSelectActivity.this, FileSelectActivity.class);
				intent.putExtras(bundle);
				FileSelectActivity.this.startActivity(intent);
			}
		}

		@Override public void onItemChecked(int pos) {
			if (index == -1) {
				index = pos;
				content.get(index).setChecked(true);
			} else if (index != -1) {
				if (pos == index) {
					content.get(index).setChecked(false);
					index = -1;
				} else {
					content.get(index).setChecked(false);
					index = pos;
					content.get(index).setChecked(true);
				}
			}
			adapter.notifyDataSetChanged();
		}
	};
}
